<?php

namespace plugin\coupon\event;

use plugin\coupon\app\model\Coupon;
use plugin\coupon\app\model\CouponReceiveLog;
use support\Db;

class UsedLog
{
    public function handle($param)
    {
        $couponReceivedModel = new CouponReceiveLog();
        $myCouponInfo = $couponReceivedModel->getInfoByWhere([
            'code' => $param['coupon'],
            'user_id' => $param['user_id'],
            'status' => 1
        ]);

        if (!empty($myCouponInfo)) {
            $couponReceivedModel->updateById([
                'order_id' => $param['order_id'],
                'status' => 2,
                'used_time' => now(),
                'update_time' => now()
            ], $myCouponInfo['id']);

            // 累计使用数量
            Db::beginTransaction();
            try {

                $couponModel = new Coupon();
                $couponModel->where('id', $myCouponInfo['coupon_id'])->lock(true)->first();
                $couponModel->where('id', $myCouponInfo['coupon_id'])->increment('used_num', 1);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
        }
    }
}
